<?php
declare (strict_types = 1);

namespace app\mall\controller;


use app\common\controller\BaseController;
use app\common\model\Config;
use app\live\model\LiveBroadcastGoods;
use app\mall\model\ActivityLog;
use app\mall\model\Goods;
use app\mall\model\GoodsAttr;
use app\mall\model\GoodsBrand;
use app\mall\model\GoodsType;
use app\mall\service\PayOrder;
use app\myself\Bc;
use app\user\model\UserLevel;
use app\user\model\UserWallet;
use app\video\model\Video;
use think\Request;

use app\order\model\Order;
use app\order\model\OrderInfo;
use app\user\model\User;
use app\shop\model\ShopCoupon;
use app\user\model\UserCoupon;

class Index extends BaseController
{
    public $no_login_actios = ['malltype','malls','getmalls','getactivitylogid','getbrand','testpay','sumTotal','shophomelist'];
    public function __construct()
    {
        parent::__construct(false);
        $this->checkLogin($this->no_login_actios);
    }

    public function index()
    {

        // 指令输出
        $oid = 300;

        $orderModel = new Order();
        $userModel = new User();
        $orderInfoModel = new OrderInfo();

        // 拿取模型数据
        $orderOrnModel = $orderModel->find($oid);
        $orderInfoIdModel = $orderInfoModel->where('oid',$orderOrnModel->id)->find();
        $userModel = $userModel->find($orderOrnModel->uid);



        // $output->writeln('---模型调用开始-------------------');

        // 调用统一处理逻辑  需要走下面的处理
        $list = $orderModel->completeOrder([
            'orderOrnModel' => $orderOrnModel,
            'orderInfoModel' => $orderInfoIdModel,
            'userModel' => $userModel
        ]);
        var_dump($list);

        exit;
        return '您好！返回'.bcdiv((string)400,(string)500,2);
    }

    // 商品分类
    public function mallType(Request $request)
    {
        $model = new GoodsType();
        $type = $request->param('type',0);
        return retu_json(200,'111商城分类ok',$model->getList($type));
    }

//  商品归类列表信息 商品搜索走此处
    public function malls(Request $request){
        $model = new Goods();
        $model->getList(Request()->param());
        // 验证用户是否有登录
        if($this->getToken()){
            // 调用 用户模型中的操作获取到单条记录
            $data = $this->user->getShareLevelData($model->list['data']);
            if($data)
                $model->list['data'] = $data;
        }
        return retu_json(200,'商品ok',$model->list);
    }

    // 爆款  、 福利 、 新品 专区
    public function shopHomeList(){
        $model = new Goods();
        $list = $model->shopList(Request()->param());
        // 验证用户是否有登录
        if($this->getToken()){
            foreach($list as $k =>&$item){
                if(strpos('title',$k) !== false){
                    // 调用 用户模型中的操作获取到单条记录
                    $data = $this->user->getShareLevelData($item);
                    if($data) $item = $data;
                }
            }
        }
        return retu_json(200,'爆款、福利、新品',$list);
    }

    // 商品详情 某一条记录，此处需要判断当前商品是否为拼团 活动等
    public function getMalls(Request $request)
    {
        $model = new Goods();
        $this->getToken();
        $model->user = $this->user;
        $list = $model->getOne(Request());
        // 如果有登录 且 不是拼团活动商品 不是 视频点击的
        if($this->getToken() && $list['bool']){
            // 声明bc函数
            $bc = new Bc();
            // 如果是层级为1  且 购买了 购物券的
            if($this->user && $this->user->level == 1 && $this->user->is_proceeds == 1) {
                $volumeConfig = (new Config())->getSrTypes('volumeVip');
                // 需要大于0
                if($volumeConfig->share && $volumeConfig->share > 0){
                    // 该用户的 比例
                    $list['commodity']['user_share'] = $volumeConfig->share;
                    // 默认折扣价
                    $list['commodity']['default_discount_price_share'] = $bc->calcDiv($volumeConfig->share /10  * $list['commodity']['old_default_discount_price'],100,2);
                }
                // 如果有身份  且 该商品有 开启分销  分享和团购省
            } else if($this->user && $this->user->getLevelModel && $this->user->getLevelModel->share > 0){
                // 该用户的 比例
                $list['commodity']['user_share'] = $this->user->getLevelModel->share;
                // 默认折扣价
                $list['commodity']['default_discount_price_share'] = $bc->calcDiv($this->user->getLevelModel->share * $list['commodity']['old_default_discount_price'],100,2);
            }
        }
        return retu_json(200,'商品详情ok',$list);
    }

    /**
     * 支付详情-获取到用户购物券  用户等级
     */
    public function payData(Request $request)
    {
        $model = new Goods();
        $list = $model->getPayData($this->user);
        return retu_json(200,$list['msg'],$list['data']);
    }

    /**
     * 发起支付
     */
    public function pay(){
        // 路由参数校验
        $this->ruleValidate([
            'id|序号'  => 'require|gt:1|number',
            'num|数量'   => 'require|number|between:1,888',
            'pay_type|支付类型' => 'require|number|between:1,2',
            'phone|收货号码' => 'require|number|min:11',
            'address|收货地址' => 'require|min:2-400',
            'name|姓名' => 'require|min:2-16',
            'attr_id|规格序号' => 'require|number|min:0'
        ]);
        $model = new Goods();
        $params = Request()->param();
        fileLog('参数数据如下：'.json_encode([
                    "user" => $this->user,
                    "前端参数" => $params
            ]),'goods_pay.log');
        //$list = $model->infoPay($this->user);
        $list = $model->newInfoPay($this->user,$params);
        fileLog('用户信息---'.json_encode($list),'支付.log');
        return retu_json(200,$list['msg'],$list['data']);
        // fileLog('发起支付错误信息：'.json_encode($list),'发起支付_error.log');
        // return retu_json(200,$list['msg'],$list['data']);
    }

    /**
     * 获取到 拼团列表中的log - id
     */
    public function getActivityLogId()
    {
        $request = Request();
        $activity_id = $request->param('activity_id',-1);
        // 没有活动id
        if(!$activity_id || $activity_id < 0)
            return retu_json(400,'活动id不存在');
        $video_id = $request->param('video_id',-1);
        // 视频id不存在
        if(!$video_id || $video_id < 0)
            return retu_json(400,'视频id不存在');
        if(!$videoModel = Video::find($video_id))
            return retu_json(400,'视频没有该记录');
        if(!$ActivityLogModel =  ActivityLog::where(['aid' => $activity_id,'uid' => $videoModel->uid])->find())
            return retu_json(400,'没有该拼团记录');
        if($ActivityLogModel->end_time - time() <= 0)
            return retu_json(400,'该拼团活动时间已结束'.($ActivityLogModel->end_time - time()));
        if($ActivityLogModel->astatus != 0)
            return retu_json(400,'该拼团已结束');
        return retu_json(200,'拿取视频关联的活动-拼团列表id-ok',['activity_log_id'=>$ActivityLogModel->id]);
    }

    /**
     * 获取到品牌列表
     */
    public function getBrand()
    {
        $this->ruleValidate(['id|id'=>'require|>:0']);
        $id = $this->getSetDefaultParams('id');
        $model =  new GoodsBrand();
        $list = $model->where('is_delete',0)->field('id,name,cover,desc,sort')->find($id);
        return retu_json(200,'品牌描述ok',$list);
    }

    /**
     * 测试中
     */
    public function testPay(){
        $data = json_decode('{"bool":true,"data":{"appid":"wx3b268c92f65ab19c","bank_type":"OTHERS","cash_fee":"1","fee_type":"CNY","is_subscribe":"N","mch_id":"1593472881","nonce_str":"1at4r3vqrstgom0i4fjf3c5vgafu61fg","openid":"o8lmR4uJaZJLasqdZXI7z36XJt4w","out_trade_no":"200914180509744284240","result_code":"SUCCESS","return_code":"SUCCESS","time_end":"20200914180520","total_fee":"1","trade_type":"JSAPI","transaction_id":"4200000702202009146878538333"},"wechat_str":"<xml><return_code><![CDATA[SUCCESS]]><\/return_code><return_msg><![CDATA[OK]]><\/return_msg><\/xml>","ip":"140.207.54.73"}',true);
        $model = new Order();
        fileLog('开始处理数据中----处理信息如下：'.json_encode($data),'微信回调开始.log');
        $list = $model->payModelNotify($data);
        dump($list);
    }


    /**
     * 计算价格
     */
    public function sumTotal()
    {
        if(!$this->user) return retu_json(402,'麻烦重新登录');
        $request = Request();
        $get = $request->param();
        // 数量不得为空
        if(!isset($get['num']) || $get['num'] <= 0) return retu_json(400, '数量不得为空');
        // 商品序号
        if(!isset($get['id']) || $get['id'] <= 0) return retu_json(400, '商品序号不得为空');
        if(!$one = Goods::find($get['id']))return retu_json(400, '没有该商品记录');
        // 商品规格序号
        if(!isset($get['attr_id']) || $get['attr_id'] <= 0) return retu_json(400, '商品规格序号不得为空');
        if(!$oneAttr = GoodsAttr::find($get['attr_id']))return retu_json(400, '没有该商品规格记录');

        // 支付处理对象声明
        $payorder =  new PayOrder();
        // 是否使用了优惠券 
        if(isset($get['coupon']) && $get['coupon'] >= 1 && $one->shop_id)$payorder->getCoupon($one,$get);

        $bc = new Bc();

        // 商品价格
        $price = $oneAttr->price;

        //是否在直播中跳转过来的
        $liveBool = isset($get['lives']) ? $get['lives'] == 'lives' : false;
        if($liveBool){
            $liveList = (new LiveBroadcastGoods())->getReGoods($get['id']);
            // 如果为true 赋值直播价
            if($liveList) $price = $oneAttr->live_price;
        }
        // 商品总额
        $goods_money = $bc->calcMul($price,$get['num'],2);
        // 总价格
        $sum_money = $bc->calcAdd($goods_money,$one->freight,2);
        

        

        // 优惠券

        // 购物券可以抵扣金额
        $wallet = 0;
        // 购物券余额
        $wallet_money = 0;
        // 本次可以使用的购物券
        $benci_wallet = 0;
        // 是否使用购物券 且 该商品符合购物券
        $walletModel = UserWallet::where('uid',$this->user->id)->find();
        if($walletModel){   
            // 购物券余额
            $wallet_money = $bc->calcDiv($walletModel->volume_balance,100,2);
            // 购物券本次可以使用金额
            $benci_wallet = $bc->calcMul($bc->calcMul($price, $bc->calcDiv($one->ticket,100,2)),$get['num']);
            // 如果大于 购物券余额
            if($benci_wallet > $wallet_money) $benci_wallet = $wallet_money;
            // 如果前端传递有使用购物券
            if(isset($get['wallet']) && $get['wallet'] == 1)$wallet =  $benci_wallet;
        }

        $money = 0;

        $configModel = new Config();
        $configList = $configModel->toData('business');
        // 默认是开启的 - 表示可以同时使用
        $purchase_volume_bool = isset($configList['purchase_volume']) && $configList['purchase_volume'] - 0;

        // 自购省金额
        $purchase = 0;
        // 不是活动订单
        if($one->is_activity == 0 || $one->is_sale == 1){
            $this->user['level'] = UserLevel::where('id',$this->user->level)->find();
            if($user = $payorder->getProportional($this->user)) $purchase = $bc->calcMul($price,$user['purchase_ratio']  * $get['num'],2);
        }

        // 如果是邮费差价
        if(strpos($one->title,'邮费差价') !== false){
            $wallet = 0;
            $purchase = 0;
        }
        
        $coupon_money = 0;

        // 如果后台配置不可以 同时使用自购 购物券 且 当前有使用购物券 或者 当前是直播
        if(($wallet > 0 && !$purchase_volume_bool) || ($liveBool && isset($liveList) && $liveList )) $purchase = 0;
        if(isset($one['coupon_bool']) && $one['coupon_bool'] && $goods_money > $one['userCoupon']['total_amount'] && $goods_money - $purchase > $one['userCoupon']['amount']){
            $coupon_money = $one['userCoupon']['amount'];
        }
        
        (float)$money = $bc->calcSub($bc->calcSub($sum_money,$coupon_money,2),$purchase,2);
        if($wallet >= $money - 0){
            $wallet = $money;
            $money = 0;
        } else $money = $bc->calcSub($money,$wallet,2);
        return retu_json(200,'计算商品价格ok',[
            'sum_money' => $sum_money,
            'money' => $money,
            'wallet' => $wallet > 0 ? $wallet : $benci_wallet,
            'wallet_money' => $wallet_money,
            'purchase' => $purchase,
            'sum_money' => $sum_money,
            'coupon_money' => $coupon_money
        ]);
    }

     /**
     * 优惠券列表 - 当前商品可领取 优惠券
     */
    public function coupon(){
        $model = new ShopCoupon();
        $this->getToken();
        $list = $model->getCouponList(Request()->param(),$this->user);
        return retu_json(200,$list['msg'],$list['data']);
    }

    /**
     * 优惠券已经领取列表 - 当前商品可使用的优惠券
     */
    public function apply_coupon(){
        $id = Request()->param('id',-1);
        if(!$id || $id <= 0)return retu_json(400,'商品记录不得为空');
        if(!$one = Goods::find($id))return retu_json(400,'没有该记录');
        $model = new UserCoupon();
        return retu_json(200,'拿取可用优惠券ok',$model->getCouponGoods($one,$this->user));
    }
}
